﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Enterprise.Framework.Cache;
using Resto.CostControl.Core.Query.SystemModule.ViewObject;
using Resto.CostControl.Core.Query.SystemModule.QueryObject;
using Enterprise.Framework.Core.Container;
using Resto.CostControl.Common.Consts;

namespace Resto.CostControl.Core.Cache
{
    /// <summary>
    /// 字典缓存，根据字典类型获取缓存项
    /// </summary>
    public class DictionaryVOArrayCache : ObjectCache<DictionaryVO[], DictionaryVOArrayCache>
    {
        static DictionaryVOArrayCache()
        {
            OnCacheObjectNotFound += FindObject;
        }

        protected override string CacheKey_Prefix
        {
            get { return "DictionaryVOCacheKey_"; }
        }

        protected override CacheMode CacheMode
        {
            get { return CacheMode.DistributedContext; }
        }


        /// <summary>
        /// 从数据库中查询微博信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private static void FindObject(object sender, CacheEventArgs args)
        {
            DictionaryQO dicQO = ObjectCreator.Create<DictionaryQO>();
            DictionaryVO[] array = dicQO.GetDictionaryArrayByType(args.Key);
            if (array != null && array.Length > 0)
            {
                args.CacheObject = array;
            }
        }

        /// <summary>
        /// 根据字典类型和Code获取字典的名称
        /// </summary>
        /// <param name="type"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string GetDicNameByCode(string type, string code)
        {
            if (type == DictionaryTypeConsts.System_DictionaryType_Code)
            {
                for (int i = 0; i < DictionaryTypeConsts.Array_DictionaryTypeCode.Length; i++)
                {
                    if (code == DictionaryTypeConsts.Array_DictionaryTypeCode[i])
                        return DictionaryTypeConsts.Array_DictionaryTypeName[i];
                }

                return string.Empty;
                     
            }

            if (string.IsNullOrWhiteSpace(code))
                return string.Empty;

            DictionaryVO[] array = Get(type);
            if (array == null)
                return string.Empty;
            DictionaryVO dic = array.FirstOrDefault(p => p.Code == code);

            if (dic != null)
                return dic.Name;
            else
                return string.Empty;
        }
    }
}
